package org.uc3m.pfc.ui;

import java.util.List;

import org.uc3m.pfc.activity.MainActivity;
import org.uc3m.pfc.data.Action;
import org.uc3m.pfc.lifecycle.State;

import android.content.Context;
import android.os.Handler;
import android.widget.Toast;

/**
 * 
 * @author esteban
 *
 */
public final class GuiUtils {

	// Class fields *******************************************************
	
	/** Static instance. */
	private static GuiUtils instance;
	
	/** Handler for executing commands in gui thread. */
	private final Handler myHandler = new Handler();

	/** Activity object. */
	private MainActivity activity;
	
	
    // Constructor *******************************************************
	
	/**
	 * Private default constructor.
	 */
	private GuiUtils() {
	}
	
	/**
	 * Get the instance.
	 * 
	 * @return static instance
	 */
	public static GuiUtils getInstance() {
		
		if (instance == null) {
			instance = new GuiUtils();
		}
		return instance;
	}

	
    // Public methods ****************************************************
	
	/**
	 * Show the actions in the options menu of activity.
	 * 
	 * @param actions for displaying
	 */
	public void showActions(final List<Action> actions) {
		final Runnable runnable = new Runnable() {
			public void run() {
				
				activity.setActions(actions);
				activity.setState(State.processing);
			}
		};

		// call the activity method that updates the UI
		invokeUiThread(runnable);
		
	}

	/**
	 * Hide the actions in the options menu of activity.
	 */
	public void hideActions() {
		final Runnable runnable = new Runnable() {
			public void run() {

				activity.setState(State.detecting);
			}
		};

		// call the activity method that updates the UI
		invokeUiThread(runnable);
		
	}
	
	/**
	 * Show a toast.
	 * 
	 * @param message message for toast
	 */
	public void showToast(final String message) {
		
		final Runnable runnable = new Runnable() {
			public void run() {
		          Toast toast = Toast.makeText(activity, message, 
		        		  Toast.LENGTH_SHORT);
		    	  
		          toast.show();
			}
		};
	
		invokeUiThread(runnable);
		
	}		
		
		
	/**
	 * Execute a command in the UI thread.
	 * 
	 * @param runnable thread to execute
	 */
	public void invokeUiThread(final Runnable runnable) {
		// update the UI using the handler and the runnable
		myHandler.post(runnable);
	}

	/**
	 * Set the activity.
	 * 
	 * @param pactivity to set
	 */
	public void setActivity(final MainActivity pactivity) {

		this.activity = pactivity;
		
	}

	/**
	 * Get the application context.
	 * 
	 * @return application context
	 */
	public Context getContext() {

		return this.activity.getApplicationContext();
	}
	
}
